/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Tools;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

/**
 *
 * @author linhduong
 */
public class XPathEngine {
    /**
     * XPath 1.0 Function: toUppercase
     * @param val
     * @return
     */
    public static String toUpperCase(String val) {
        if(val==null||val.isEmpty()) return "";
        String rel;
        if(val.charAt(0)=='#') {
          rel = "translate(\"";
          rel+= val.substring(1, val.length());
          rel+="\",\"abcdefghijklmnopqrstuvwxyz\",\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")";
        }
        else
          rel = "translate(" +val + ",\"abcdefghijklmnopqrstuvwxyz\",\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")";
        return rel;
    }

    /**
     * XPATH 1.0 Function: ToLowerCase
     * @param val
     * @return
     */
    public static String toLowerCase(String val) {
        if(val==null||val.isEmpty()) return "";
        String rel;
        if(val.charAt(0)=='#') {
          rel = "translate(\"";
          rel+= val.substring(1, val.length());
          rel+="\",\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\"abcdefghijklmnopqrstuvwxyz\")";
        }
        else
          rel = "translate(" +val + ",\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\"abcdefghijklmnopqrstuvwxyz\")";
        return rel;
    }

    /**
     * Query a document to node list
     * @param doc
     * @param query
     * @return
     * @throws XPathExpressionException
     */
    public static NodeList queryDocument(Document doc, String query) throws XPathExpressionException {
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xpath.compile(query);
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        return ((NodeList) result);
    }
}
